#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include "common.h"

void get_command(char * buffer)
{
    fgets(buffer, MAX_COMMAND_LENGTH, stdin);
    buffer[strlen(buffer)-1] = 0;
}

int is_white(char character, char * character_set) 
{
  int i;
  for (i = 0; character_set[i] != 0; i++)
    if (character == character_set[i])
      return 1;
  return 0;
}


char * copy_token(char * string, char * character_set) 
{
  int length = 0;
  for (length = 0; string[length] != 0 && !is_white(string[length], character_set); length++) {
  }
  char * copy = my_malloc((length + 1)*sizeof(char));
  for (length = 0; string[length] != 0 && !is_white(string[length], character_set); length++) {
	copy[length] = string[length];
  }
  copy[length] = 0;
  return copy;
}

void split(char * string, char * character_set, char * * tokens) 
{
  if (string[0] == 0) {
    return;
  }

  int i = 0;
  int token_count = 0;

  if (!is_white(string[0], character_set)) {
    tokens[token_count++] = copy_token(string, character_set);
  }

  while (string[i+1] != 0) {
    int current_white = is_white(string[i], character_set);
    int next_starts_token = !is_white(string[i+1], character_set) && string[i+1] != 0;
    if (current_white && next_starts_token) {
	tokens[token_count++] = copy_token(string + i + 1, character_set);
    }
    i++;
  }
  tokens[token_count] = 0;
}

void purge(char * * array) 
{
  int i;
  for (i =0; array[i] != 0; i++)
    my_free(array[i]);
}

int _malloc_counter = 0;

void * my_malloc(size_t siz)
{
  _malloc_counter++;
  return malloc(siz);
}

void my_free(void *mem)
{
  _malloc_counter--;
  free(mem);
}

void my_assert_malloc_ok() 
{
  dprint("Allocs: %d\n", _malloc_counter);
  assert(_malloc_counter == 0);
}

